package com.sw.bbs.board.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sw.bbs.board.dao.BoardPostMapper;
import com.sw.bbs.board.dao.CommentMapper;
import com.sw.bbs.board.dao.PostMapper;
import com.sw.bbs.board.dao.media.TagMapper;
import com.sw.bbs.board.dao.user.UserPostMapper;
import com.sw.bbs.board.pojo.BoardPost;
import com.sw.bbs.board.pojo.Comment;
import com.sw.bbs.board.pojo.Post;
import com.sw.bbs.board.pojo.Tag;
import com.sw.bbs.board.pojo.user.UserPost;
import com.sw.bbs.board.service.PostService;
import com.sw.bbs.board.service.TagService;
import com.sw.bbs.board.vo.request.comment.QueryCommentRequest;
import com.sw.bbs.board.vo.request.post.InsertPostRequest;
import com.sw.bbs.board.vo.request.post.QueryPostRequest;
import com.sw.bbs.board.vo.request.post.UpdatePostRequest;
import com.sw.bbs.board.vo.response.FollowBoardPostResponse;
import com.sw.bbs.board.vo.response.post.PostDetailResponse;
import com.sw.bbs.board.vo.response.post.PostListResponse;
import com.sw.bbs.common.util.ContentTransUtils;
import com.sw.bbs.user.pojo.User;
import com.sw.bbs.user.service.UserService;
import com.sw.bbs.user.vo.response.UserListResponse;
import lombok.Synchronized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Service
public class PostServiceImpl implements PostService {

    private static final Logger logger = LoggerFactory.getLogger(PostServiceImpl.class);

    @Autowired
    private UserService authService;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private BoardPostMapper boardPostMapper;

    @Autowired
    private UserPostMapper userPostMapper;

    @Autowired
    private TagService tagService;

    @Override
    public PageInfo<PostListResponse> queryPostList(QueryPostRequest request) {
        PageHelper.startPage(request.getOffset(), request.getLimit());
        List<PostListResponse> postList = postMapper.queryPostList(request);
        return PageInfo.of(postList);
    }

    @Override
    public PostDetailResponse queryPostDetail(Integer postId) {

        PostDetailResponse detailResponse = new PostDetailResponse();
        Post post = postMapper.selectByPrimaryKey(postId);
        detailResponse.setPost(post);

        UserListResponse userListResponse = postMapper.queryUserByPostId(postId);
        detailResponse.setUser(userListResponse);

        return detailResponse;
    }

    /**
     * 插入
     *
     * @param insertboardPostRequest
     * @param httpServletRequest
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    @Synchronized
    public Integer insertPost(InsertPostRequest insertboardPostRequest,
                              HttpServletRequest httpServletRequest) throws Exception {

        User user = authService.getUserByRequest(httpServletRequest);
        Post post = new Post();
        BeanUtils.copyProperties(insertboardPostRequest, post);

        //提取#话题

        Map<String,List> map = ContentTransUtils.getContentInfo(post.getContent());
        List<String> tags = map.get("tags");
        tagService.updateAndInsertTags(tags);

        try {
            int result = postMapper.insertSelective(post);
            if (result > 0) {
                Integer postId = post.getPostId();
                //插入关系表
                if (insertboardPostRequest.getBoardId() != null) {
                    BoardPost boardPost = new BoardPost();
                    boardPost.setBoardId(insertboardPostRequest.getBoardId());
                    boardPost.setPostId(postId);
                    result = boardPostMapper.insertSelective(boardPost);
                    if (result <= 0) {
                        logger.info("insert boardPostMapper fail");
                        throw new RuntimeException("insert boardPostMapper fail");
                    }

                    UserPost userPost = new UserPost();
                    userPost.setPostId(postId);
                    userPost.setUserId(user.getUserId());
                    result = userPostMapper.insertSelective(userPost);
                    if (result <= 0) {
                        logger.info("insert boardPostMapper fail");
                        throw new RuntimeException("insert boardPostMapper fail");
                    }
                }

            } else {
                logger.info("insert post fail");
                throw new RuntimeException("insert post fail");
            }
            return result;

        } catch (Exception e) {

            logger.info("insert post fail");
            throw new RuntimeException("insert post fail");
        }


    }

    /**
     * 更新帖子
     *
     * @param updatePostRequest
     * @return
     */
    @Override
    @Transactional
    @Synchronized
    public Integer updatePost(UpdatePostRequest updatePostRequest) throws Exception {

        Post post = new Post();
        BeanUtils.copyProperties(updatePostRequest, post);
        try {
            return postMapper.updateByPrimaryKeySelective(post);
        } catch (Exception e) {
            logger.info("update post fail");
            throw new RuntimeException("update post fail");
        }
    }

    /**
     * 删除
     *
     * @param postId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    @Synchronized
    public Integer deletePost(Integer postId) throws Exception {

        try {
            return postMapper.deleteByPrimaryKey(postId);
        } catch (Exception e) {
            logger.info("delete post fail");
            throw new RuntimeException("delete post fail");
        }
    }

    /**
     * 热门帖子
     * @return
     */
    @Override
    public List<PostListResponse> queryHotPostList() {
        QueryPostRequest request = new QueryPostRequest();
        request.setSortField("p.follow_num desc,p.collect_num desc,p.read_num desc");
        request.setOnceQuery(1);
        List<PostListResponse> postList = postMapper.queryPostList(request);
        return postList;
    }


}
